﻿#region [ License information          ]
/* ************************************************************
 *
 * Copyright (c) Bjørn Bouet Smith, 2010, 2011
 *
 * This source code is subject to terms and conditions of 
 * Microsoft Public License (Ms-PL).
 * 
 * A copy of the license can be found in the license.txt
 * file at the root of this distribution. If you can not 
 * locate the License, please send an email to bjornsmith@gmail.com
 * 
 * By using this source code in any fashion, you are 
 * agreeing to be bound by the terms of the Microsoft 
 * Permissive License.
 *
 * You must not remove this notice, or any other, from this
 * software.
 *
 * ************************************************************/
#endregion

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Smith.AMC.PerformanceCounters
{
    /// <summary>
    /// The performance counters.
    /// </summary>
    public class PerformanceCounterController : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PerformanceCounterController"/> class.
        /// </summary>
        /// <param name="instanceName">The instance name to use for the performance counters.
        /// Send null to use no instance name.</param>
        public PerformanceCounterController(string instanceName)
        {
            if (!PerformanceCounterCategory.Exists(PerformanceCounterInstaller.PerformanceCounterCategoryName))
            {
                throw new InvalidOperationException("Performance counters have not been installed yet");
            }

            CreateCounters(instanceName);
        }

        /// <summary>
        /// Gets TotalCacheOperationsPerSecond.
        /// </summary>
        public PerformanceCounter TotalCacheOperationsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets AddsPerSecond.
        /// </summary>
        public PerformanceCounter AddsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets AppendsPerSecond.
        /// </summary>
        public PerformanceCounter AppendsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets CASPerSecond.
        /// </summary>
        public PerformanceCounter CASPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets DeletesPerSecond.
        /// </summary>
        public PerformanceCounter DeletesPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets ReplacesPerSecond.
        /// </summary>
        public PerformanceCounter ReplacesPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets PrependsPerSecond.
        /// </summary>
        public PerformanceCounter PrependsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets SetsPerSecond.
        /// </summary>
        public PerformanceCounter SetsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets ErrorsPerSecond.
        /// </summary>
        public PerformanceCounter ErrorsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets GetsPerSecond.
        /// </summary>
        public PerformanceCounter GetsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets IncrementsPerSecond.
        /// </summary>
        public PerformanceCounter IncrementsPerSecond
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets DecrementsPerSecond.
        /// </summary>
        public PerformanceCounter DecrementsPerSecond
        {
            get;
            private set;
        }


        /// <summary>
        /// Gets AverageSocketWaitTime.
        /// </summary>
        private PerformanceCounter AverageSocketWaitTime
        {
            get;
            set;
        }

        /// <summary>
        /// Gets AverageSocketWaitTime base
        /// </summary>
        private PerformanceCounter AverageSocketWaitTimeBase
        {
            get;
            set;
        }

        /// <summary>
        /// Increments the average time for waiting for a socket.
        /// </summary>
        /// <param name="ticksSpent">The number of ticks spent.</param>
        public void IncrementAverageTime(long ticksSpent)
        {
            AverageSocketWaitTime.IncrementBy(ticksSpent);
            AverageSocketWaitTimeBase.Increment();
        }

        /// <summary>
        /// Gets the current ticks by querying the performance counters
        /// </summary>
        /// <returns>the current ticks in the system</returns>
        public long GetCurrentTicks()
        {
            long ticks = 0;
            QueryPerformanceCounter(ref ticks);
            return ticks;
        }

        [DllImport("Kernel32.dll")]
        private static extern void QueryPerformanceCounter(ref long ticks);

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            AddsPerSecond.RemoveInstance();
            AddsPerSecond.Dispose();
            AddsPerSecond = null;

            AppendsPerSecond.RemoveInstance();
            AppendsPerSecond.Dispose();
            AppendsPerSecond = null;

            AverageSocketWaitTime.RemoveInstance();
            AverageSocketWaitTime.Dispose();
            AverageSocketWaitTime = null;

            AverageSocketWaitTimeBase.RemoveInstance();
            AverageSocketWaitTimeBase.Dispose();
            AverageSocketWaitTimeBase = null;

            CASPerSecond.RemoveInstance();
            CASPerSecond.Dispose();
            CASPerSecond = null;

            DeletesPerSecond.RemoveInstance();
            DeletesPerSecond.Dispose();
            DeletesPerSecond = null;

            ErrorsPerSecond.RemoveInstance();
            ErrorsPerSecond.Dispose();
            ErrorsPerSecond = null;

            PrependsPerSecond.RemoveInstance();
            PrependsPerSecond.Dispose();
            PrependsPerSecond = null;

            ReplacesPerSecond.RemoveInstance();
            ReplacesPerSecond.Dispose();
            ReplacesPerSecond = null;

            SetsPerSecond.RemoveInstance();
            SetsPerSecond.Dispose();
            SetsPerSecond = null;

            TotalCacheOperationsPerSecond.RemoveInstance();
            TotalCacheOperationsPerSecond.Dispose();
            TotalCacheOperationsPerSecond = null;

            GetsPerSecond.RemoveInstance();
            GetsPerSecond.Dispose();
            GetsPerSecond = null;

            IncrementsPerSecond.RemoveInstance();
            IncrementsPerSecond.Dispose();
            IncrementsPerSecond = null;

            DecrementsPerSecond.Dispose();
            DecrementsPerSecond = null;
        }

        /// <summary>
        /// Creates the performance counter with the given name and instance
        /// </summary>
        /// <param name="name">The name of the performance counter.</param>
        /// <param name="instanceName">Name of the instance.</param>
        /// <returns>The performance counter that was created.</returns>
        private static PerformanceCounter CreateCounter(string name, string instanceName)
        {
            var counter = new PerformanceCounter
            {
                CategoryName = PerformanceCounterInstaller.PerformanceCounterCategoryName,
                CounterName = name,
                MachineName = ".",
                //InstanceName = string.IsNullOrEmpty(instanceName) ? "Default" : instanceName,
                ReadOnly = false,
                //InstanceLifetime = PerformanceCounterInstanceLifetime.Process
            };
            counter.RawValue = 0;
        
            return counter;
        }

        /// <summary>
        /// Creates all the needed counters
        /// </summary>
        /// <param name="instanceName">Name of the instance.</param>
        private void CreateCounters(string instanceName)
        {
            AddsPerSecond = CreateCounter(PerformanceCounterNames.AddsPerSecond, instanceName);
            AppendsPerSecond = CreateCounter(PerformanceCounterNames.AppendsPerSecond, instanceName);
            AverageSocketWaitTime = CreateCounter(PerformanceCounterNames.AverageSocketWaitTime, instanceName);
            AverageSocketWaitTimeBase = CreateCounter(PerformanceCounterNames.AverageSocketWaitTimeBase, instanceName);
            CASPerSecond = CreateCounter(PerformanceCounterNames.CASPerSecond, instanceName);
            DeletesPerSecond = CreateCounter(PerformanceCounterNames.DeletesPerSecond, instanceName);
            ErrorsPerSecond = CreateCounter(PerformanceCounterNames.ErrorsPerSecond, instanceName);
            PrependsPerSecond = CreateCounter(PerformanceCounterNames.PrependsPerSecond, instanceName);
            ReplacesPerSecond = CreateCounter(PerformanceCounterNames.ReplacesPerSecond, instanceName);
            SetsPerSecond = CreateCounter(PerformanceCounterNames.SetsPerSecond, instanceName);
            GetsPerSecond = CreateCounter(PerformanceCounterNames.GetsPerSecond, instanceName);
            IncrementsPerSecond = CreateCounter(PerformanceCounterNames.IncrementsPerSecond, instanceName);
            DecrementsPerSecond = CreateCounter(PerformanceCounterNames.DecrementsPerSecond, instanceName);
            TotalCacheOperationsPerSecond = CreateCounter(PerformanceCounterNames.TotalCacheOperationsPerSecond, instanceName);
        }
    }
}